﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web;
using System.Web.Mvc;

namespace System.Web.Mvc
{
    /*

     1.
      
     ViewData["latestPosts"] = new PartialRequest(new { 
      controller = "Blog", 
      action = "LatestPosts" 
     });
     <% ((PartialRequest)ViewData["partialAction"]).Invoke(ViewContext); %>

     2.
      
     Html.RenderPartialRequest(new PartialRequest(new
     {
       controller = “YourController”,
       action = “YourAction”
     }));
     
     
     3.
      
     Html.RenderPartialRequest(new {controller=”Model”, action=”Panel_AddProfile” });
     
     */

    /// <summary>
    /// http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/
    /// </summary>
    public static class PartialRequestsExtensions
    {
        public static void RenderPartialRequest(this HtmlHelper html, PartialRequest partial)
        {
            if (partial != null)
            {
                partial.Invoke(html.ViewContext);
            }
        }

        public static void RenderPartialRequest(this HtmlHelper html, object routeValues)
        {
            PartialRequest partial = new PartialRequest(routeValues);
            html.RenderPartialRequest(partial);
        }

        public static void RenderPartialRequest(this HtmlHelper html, string viewDataKey)
        {
            PartialRequest partial = html.ViewContext.ViewData.Eval(viewDataKey) as PartialRequest;
            html.RenderPartialRequest(partial);
        }
    }

    public class PartialRequest
    {
        public RouteValueDictionary RouteValues { get; private set; }

        public PartialRequest(object routeValues)
        {
            RouteValues = new RouteValueDictionary(routeValues);
        }

        public void Invoke(ControllerContext context)
        {
            RouteData rd = new RouteData(context.RouteData.Route, context.RouteData.RouteHandler);
            foreach (var pair in RouteValues)
                rd.Values.Add(pair.Key, pair.Value);
            IHttpHandler handler = new MvcHandler(new RequestContext(context.HttpContext, rd));
            handler.ProcessRequest(System.Web.HttpContext.Current);
        }
    }
}
